<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Category_model extends MY_Model
{
	public $_table = 'categories';

	public function __construct()
	{
		parent::__construct();
	}

	public function list_all($parent_id = 0)
	{
		$categories = array();

		$this->db->where('parent_id', $parent_id);
		$this->db->order_by('position asc');

		$query = $this->db->get($this->_table);

		if ($query->num_rows())
		{
			$parent_categories = $query->result();
			foreach ($parent_categories as $key => $category)
			{
				$categories[$key]['cat'] = $category;
				$categories[$key]['childrent'] = $this->list_all($category->id);
			}
		}

		return $categories;
	}

	public function build_dropdown($field_name = 'parent_id', $extra = '')
	{
		$categories = $this->list_all();
		$html = "<select name=\"{$field_name}\" {$extra}>\n";
		$html.= "<option value=\"0\">--</option>\n";
		$this->build_list($categories, $html, 0, 'option');
		$html.= "</select>\n";

		return $html;
	}

	public function build_list($categories, &$html = "", $level = 0, $tag = "")
	{
		$this->load->helper('string');
		if (!empty($categories))
		{
			foreach ($categories as $childrent)
			{
				if($tag == "option")
				{
					$html.= "<option value=\"{$childrent['cat']->id}\">".repeater('&nbsp;&nbsp;&nbsp;&nbsp;', $level).$childrent['cat']->name."</option>\n";
				}
				else
				{
					$html.= repeater('&nbsp;&nbsp;&nbsp;&nbsp;', $level).$childrent['cat']->name."\n";
				}

				$this->build_list($childrent['childrent'], $html, $level+1, $tag);
			}
		}
	}

	public function get_single_path($category_id)
	{
	}

	public function get_childrent($category_id)
	{
	}

	public function delete($category_id)
	{
	}

	public function single_path($list, &$category = array(), $parent = "", $split = "&raquo;")
	{
		foreach ($list as $childrent)
		{
			$category[$childrent['cat']->id]['name'] = $parent . $childrent['cat']->name;
			$category[$childrent['cat']->id]['description'] = $childrent['cat']->description;
			$category[$childrent['cat']->id]['position'] = $childrent['cat']->position;

			$next_node = !$parent ? $childrent['cat']->name . " {$split} " . $parent : $parent . $childrent['cat']->name ." {$split} ";

			$this->single_path($childrent['childrent'], $category, $next_node);
		}
	}
}